# encoding: utf-8

class CommentsController < ApplicationController
	before_filter :load_sidebar
	before_filter :require_login
	before_filter :allow_self_only, :except => :create
	def allow_self_only
		comment = Comment.find(params[:id])
		if( comment.member.id != current_member.id and not current_member.is_admin? )
			redirect_to root_url
		end
	end

	def create
		comment = Comment.new( params[:comment] )
		comment.member = current_member

		unless params[:post_id].nil?
			post = Post.find(params[:post_id])
		comment.commentable = post
		end

		if params[:tutorial_id] != nil
			tutorial = Tutorial.find(params[:tutorial_id])
		comment.commentable = tutorial
		end

		comment.save

		redirect_to comment.commentable.url
	end

	def destroy
		comment = Comment.find(params[:id])
		redirect_url = comment.post.url
		comment.destroy

		redirect_to redirect_url
	end

	def edit
		@comment = Comment.find(params[:id])
	end

	def update
		@comment = Comment.find( params[:id])

		if @comment.update_attributes( params[:comment] )
			redirect_to @comment.post.url
		else
			render :action => :edit
		end
	end

end
